﻿using FangPage.Common;
using FangPage.Core;
using FangPage.Data;
using ProjectManager.User.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProjectManager.User.Controller
{
    public class depart_edit : FPController
    {
        protected string id = FPRequest.GetString("id");

        protected string parentid = FPRequest.GetString("parentid");

        protected Department departinfo = new Department();

        public override void Controller()
        {
            AuthInfo authinfo = Logins.Authorize();

            if (!authinfo.islogin)
            {
                FPResponse.ShowErr("对不起，您尚未登录或登录超时！", isview);
                return;
            }

            if (!id.IsNullOrEmpty())
            {
                departinfo = DbHelper.ExcuteModel<Department>(id);
                parentid = departinfo.parentid;
            }
            else
            {
                departinfo.parentid = parentid;
            }

            if(ispost)
            {
                departinfo = FPRequest.GetModel(departinfo);

                if(departinfo.id.IsNullOrEmpty())
                {
                    DbHelper.ExcuteInsert(departinfo);

                    FPResponse.WriteSuccess("添加成功");
                }
                else
                {
                    DbHelper.ExcuteUpdate(departinfo);

                    FPResponse.WriteSuccess("修改成功");
                }
            }

            if (id.IsNullOrEmpty())
            {
                List<SqlParam> where = new List<SqlParam>();

                if (parentid.IsNullOrEmpty())
                {
                    where.Add(DbHelper.MakeOrWhere("parentid", WhereType.IsNullOrEmpty));
                }
                else
                {
                    where.Add(DbHelper.MakeAndWhere("parentid", parentid));
                }

                departinfo.sortindex = DbHelper.ExcuteCount<Department>(where.ToArray()) + 1;
            }
        }
    }
}
